export const compareJson = (oldObj, newObj, currentPath = []) => {
    const differences = []

    // 检查是否为对象或数组，以及是否为null
    if (
        typeof oldObj !== 'object' ||
        typeof newObj !== 'object' ||
        oldObj === null ||
        newObj === null
    ) {
        if (oldObj !== newObj) {
            differences.push({
                path: [...currentPath],
                oldValue: oldObj,
                newValue: newObj
            })
        }
        return differences
    }

    // 检查是否为数组
    if (Array.isArray(oldObj) || Array.isArray(newObj)) {
        if (!Array.isArray(oldObj) || !Array.isArray(newObj)) {
            differences.push({
                path: [...currentPath],
                oldValue: oldObj,
                newValue: newObj
            })
            return differences
        }

        // 数组长度不同
        if (oldObj.length !== newObj.length) {
            differences.push({
                path: [...currentPath],
                oldValue: oldObj,
                newValue: newObj
            })
            return differences
        }

        // 递归比较数组元素
        for (let i = 0; i < oldObj.length; i++) {
            differences.push(
                ...compareJson(oldObj[i], newObj[i], [...currentPath, i])
            )
        }
        return differences
    }

    // 获取所有键
    const allKeys = new Set([...Object.keys(oldObj), ...Object.keys(newObj)])

    // 遍历所有键并递归比较值
    for (const key of allKeys) {
        const path = [...currentPath, key]

        if (!(key in oldObj)) {
            differences.push({
                path,
                oldValue: undefined,
                newValue: newObj[key]
            })
        } else if (!(key in newObj)) {
            differences.push({
                path,
                oldValue: oldObj[key],
                newValue: undefined
            })
        } else {
            differences.push(...compareJson(oldObj[key], newObj[key], path))
        }
    }

    return differences
}
